# !/home/***/anaconda3/bin/python #选择合适的python版本
"""
    xpan upload
    include:
        precreate
        upload
        create
"""
import os
import sys
import re
BASE_DIR = os.path.dirname ( os.path.dirname ( os.path.abspath ( __file__ ) ) )
sys.path.append ( BASE_DIR )
from pprint import pprint
from openapi_client.api import fileupload_api
import openapi_client
import hashlib
import os
import tempfile
def precreate () :
  """
  precreate
  """
  access_token = "126.c56c6366595dcc417c8a2c0a99e735b2.YmiHXOj071iMcLnenlTyExzPJiZ0ZBb3Xn0qS4Q.xevO2w"  # 填入自己的access_token
  path = "/apps/text/ep436.rar" # str | 对于一般的第三方软件应用，路径以 "/apps/your-app-name/" 开头。对于小度等硬件应用，路径一般 "/来自：小度设备/" 开头。对于定制化配置的硬件应用，根据配置情况进行填写。
  file_path = "D:/eeeeeeeee/ep436.rar"  # 要上传的文件的真实路径

  # 获取临时文件夹路径
  temp_dir = tempfile.gettempdir ( )
  print ( f"临时文件夹路径: {temp_dir}" )

  # 获取当前文件路径
  current_file_path = os.path.dirname ( file_path )
  print ( f"获取当前文件路径: {current_file_path}" )
  # 获取文件名
  basename = os.path.basename ( file_path )
  print ( f"文件名: {basename}" )

  # 获取文件名（不包含路径和扩展名）
  file_name = os.path.splitext ( basename ) [ 0 ]
  print ( f"获取文件名（不包含路径和扩展名）: {file_name}" )
  # 创建缓存路径
  folder_path = temp_dir + "/" + "BaiDuSync/" + file_name + "Temp"

  # 创建存储切片文件的文件夹，如果文件夹不存在
  if not os.path.exists ( folder_path ) :
    os.makedirs ( folder_path )

  file_path_temp_list = [ ]
  sorted_list = []

  block_list = '['
  isdir = 0  # int | isdir
  autoinit = 1  # int | autoinit
  rtype = 3  # int | rtype (optional)

  #    Enter a context with an instance of the API client
  with openapi_client.ApiClient ( ) as api_client :
    # Create an instance of the API class
    api_instance = fileupload_api.FileuploadApi ( api_client )
    with open ( file_path , 'rb' ) as f :
      size = os.path.getsize ( file_path )
      chunk_size = 4 * 1024 * 1024
      if size > chunk_size :
        index = 0
        chunk = f.read ( chunk_size )
        while chunk :
          chunk_file_path = os.path.join ( folder_path , f"{basename}.{chunk_size}.{index}" )
          sorted_list.append ( chunk_file_path )
          #file_path_temp_list.append ( chunk_file_path )

          with open ( chunk_file_path , 'wb' ) as chunk_file :
            chunk_file.write ( chunk )
            index += 1
            chunk = f.read ( chunk_size )
          with open ( chunk_file_path , 'rb' ) as chunk_file_md5 :
            data = chunk_file_md5.read ( )
            file_md5 = hashlib.md5 ( data ).hexdigest ( )  # 获取上传文件md5
            block_list += '"{}",'.format ( file_md5 )  # 放入block_list

  #sorted_list = sorted ( file_path_temp_list , key = sort_files )
  '''
    with open ( file_path , 'rb' ) as f :
      size = os.path.getsize ( file_path )
      chunk_size = 4 * 1024 * 1024
      if size > chunk_size:
        index = 0
        chunk = f.read ( chunk_size )
        while chunk :
          with open ( f"{file_path}.{chunk_size}.{index}" , 'wb' ) as chunk_file :
            chunk_file.write ( chunk )
            index += 1
            chunk = f.read ( chunk_size )
    folder_path= "D:/eeeeeeeee/temp/"
    if not os.path.exists(folder_path):
      os.makedirs( folder_path)
    
    file_path_temp_list = []
    for file_name in os.listdir ( folder_path) :

    
      file_path_temp = os.path.join(folder_path,file_name)
      file_path_temp_list.append ( file_path_temp )
      
      sorted_list = sorted ( file_path_temp_list , key = sort_files )
      #print(sorted_list)'''
  '''
  for tmp in sorted_list:
    
    with open ( tmp , 'rb' ) as f :
      data = f.read ( )
      file_md5 = hashlib.md5 ( data ).hexdigest ( )  # 获取上传文件md5
      block_list += '"{}",'.format ( file_md5 ) # 放入block_list
      '''
  size = os.path.getsize ( file_path )  # 获取上传文件大小

  block_list = block_list[:-1]  + "]"
  try :
    api_response = api_instance.xpanfileprecreate ( access_token , path , isdir , size , autoinit , block_list , rtype = rtype )
    pprint ( api_response )
    uploadid = api_response [ 'uploadid' ]  # 获取预上传返回的uploadid，传给upload和create函数
  except openapi_client.ApiException as e :
    print ( "Exception when calling FileuploadApi->xpanfileprecreate: %s\n" % e )
  #return access_token , path , isdir , size , uploadid , block_list , rtype , file_path
  upload (  access_token , path , isdir , size , autoinit , block_list,rtype,uploadid,file_path,folder_path,api_response,sorted_list,)

def sort_files ( file_name ) :
  # 使用正则表达式提取文件名中的数字部分
  file_number = re.search ( r'\.(\d+)$' , file_name ).group ( 1 )
  # 将提取的数字部分转换为整数，用于排序
  number = int ( file_number )
  return number
def upload (  access_token , path , isdir , size , autoinit , block_list,rtype,uploadid,file_path,folder_path,api_response,sorted_list) :
  """
  upload
  """
  print(path)
  #print(api_response["block_list"])
  # Enter a context with an instance of the API client
  with openapi_client.ApiClient ( ) as api_client :
    # Create an instance of the API class
    api_instance = fileupload_api.FileuploadApi ( api_client )
  type = "tmpfile"  # str |
  try :
    for num in range ( len (sorted_list )) :
      #print(num)
      partseq = str ( num )  # str |
      file = open ( sorted_list[num], 'rb' )
      # example passing only required values which don't have defaults set
      # and optional values
      try :
        api_response = api_instance.pcssuperfile2 ( access_token , partseq , path , uploadid , type , file = file )
        #print ( api_response )
      except openapi_client.ApiException as e :
        print ( "Exception when calling FileuploadApi->pcssuperfile2: %s\n" % e )

  except Exception as e :
    print ( "Exception when open file: %s\n" % e )
    exit ( -1 )


  create(  access_token , path , isdir , size , autoinit , block_list,rtype,uploadid,file_path,folder_path)

def create (  access_token , path , isdir , size , autoinit , block_list,rtype,uploadid,file_path,folder_path ) :
  """
  create
  """
  # Enter a context with an instance of the API client
  with openapi_client.ApiClient ( ) as api_client :
    # Create an instance of the API class
    api_instance = fileupload_api.FileuploadApi ( api_client )
    # example passing only required values which don't have defaults set
    # and optional values
    try :
      api_response = api_instance.xpanfilecreate ( access_token , path , isdir , size , uploadid , block_list , rtype = rtype )
      print(block_list)
      pprint ( api_response )
    except openapi_client.ApiException as e :
      print ( "Exception when calling FileuploadApi->xpanfilecreate: %s\n" % e )
  import shutil
  shutil.rmtree ( folder_path )
  #delete_folder ( folder_path )
def delete_folder ( path ) :
  try :
    os.removedirs ( path )
    print ( f"成功删除文件夹 {path}" )
  except OSError as e :
    print ( f"删除文件夹 {path} 失败: {e}" )

if __name__ == '__main__' :
  precreate ( )
  #access_token , path , isdir , size , uploadid , block_list , rtype , file_path = precreate ( )
  #upload ( uploadid , path , file_path , access_token )
  #create ( access_token , path , isdir , size , uploadid , block_list , rtype )



